package com.yfqy.app.configure;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        // 允许的域名，* 表示允许所有域名，生产环境建议指定具体域名
        response.setHeader("Access-Control-Allow-Origin", getAllowOrigin(request));

        // 允许的请求方法
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");

        // 预检请求的缓存时间（秒）
        response.setHeader("Access-Control-Max-Age", "3600");

        // 允许的请求头
        response.setHeader("Access-Control-Allow-Headers", getAllowHeaders());

        // 允许暴露的响应头
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition, Authorization, X-Total-Count");

        // 是否允许携带凭证（cookies、认证信息等）
        response.setHeader("Access-Control-Allow-Credentials", "true");

        // 处理预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        chain.doFilter(req, res);
    }

    /**
     * 获取允许的 Origin
     */
    private String getAllowOrigin(HttpServletRequest request) {
        String origin = request.getHeader("Origin");
        // 这里可以添加域名白名单逻辑
        if (isAllowedOrigin(origin)) {
            return origin;
        }
        // 默认允许所有，生产环境建议返回具体域名
        return "*";
    }

    /**
     * 域名白名单检查
     */
    private boolean isAllowedOrigin(String origin) {
        if (origin == null || origin.isEmpty()) {
            return false;
        }

        // 在这里配置允许的域名
        String[] allowedOrigins = {
                "http://localhost:3000",
                "http://localhost:5173",
                "http://localhost:8081",
                "http://localhost:18081",
                "https://yourdomain.com",
                "https://www.yourdomain.com"
        };

        for (String allowedOrigin : allowedOrigins) {
            if (allowedOrigin.equals(origin)) {
                return true;
            }
        }

        // 开发环境允许所有，生产环境建议返回 false
        return true;
    }

    /**
     * 获取允许的请求头
     */
    private String getAllowHeaders() {
        return String.join(", ",
                "Authorization",
                "Content-Type",
                "X-Requested-With",
                "Accept",
                "Origin",
                "Access-Control-Request-Method",
                "Access-Control-Request-Headers",
                "X-CSRF-TOKEN",
                "X-Token",
                "Timestamp",
                "Signature",
                "Sign",
                "User-Agent",
                "Cache-Control"
        );
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化逻辑，如果需要的话
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        // 清理逻辑，如果需要的话
        Filter.super.destroy();
    }
}